package com.na.flipcard.ui;

import java.util.Hashtable;
import java.util.Map.Entry;
import java.util.Set;

import android.graphics.Color;
import android.graphics.Rect;
import android.view.MotionEvent;

import com.na.flipcard.util.GameConfigEx;
import com.na.flipcard.util.GameUtil;
import com.na.flipcard.util.NormalEventListener;
import com.na.flipcard.util.UpdateAdPointListener;
import com.na.game.GameManager;
import com.na.game.data.DataManager;
import com.na.game.event.EventListener;
import com.na.game.event.Updater;
import com.na.game.event.impl.EventAdapter;
import com.na.game.event.impl.TouchEvent;
import com.na.game.graphics.Graphics;
import com.na.game.graphics.Image;
import com.na.game.graphics.Painter;
import com.na.game.platform.ad.Ad;
import com.na.game.platform.ad.AdPoints;
import com.na.game.platform.pay.PayListener;
import com.na.game.platform.pay.PayManager;
import com.na.game.platform.sns.SnsManager;
import com.na.game.props.PropsManager;
import com.na.game.props.PropsManager.GamePropsDef;
import com.na.game.resource.ResourceManager;
import com.na.game.sound.SoundManager;
import com.na.game.ui.UI;
import com.na.game.ui.UIManager;
import com.na.game.util.GameConfig;
import com.na.game.util.Util;
import com.na.game.util.Util.NormalBgPainter;
import com.na.game.widget.Layout;
import com.na.game.widget.Widget;
import com.na.game.widget.impl.Button;
import com.na.game.widget.impl.Container;
import com.na.game.widget.impl.Label;
import com.na.game.widget.impl.TextArea;

public class StartGameUI extends UI {

	private Container propsAmount;
	private Label myGold;
	private Label totalCost;
	private int cost;
	private TextArea desc;
	private Button[] propsBtns;
	private GamePropsDef touchProps;
	
//	private boolean showToast = true;
	
	private Hashtable<GamePropsDef, Integer> props = new Hashtable<GamePropsDef, Integer>();
	
	@Override
	public void init() {
		Ad.getAd().getPoints(new AdPointsListener());
		
		Container ui = new Container();
		ui.setBound(0, 0, GameConfig.STANDARD_WIDTH, GameConfig.STANDARD_HEIGHT);
		ui.setPainter(new NormalBgPainter(ui));
		setWidget(ui);
		
		ResourceManager rm = GameManager.get(ResourceManager.class);
		
		Image image = rm.getImageFromAssets(GameConfigEx.RES_COIN);
		
		int w = Util.getTextWidth("当前选择的道具");
		int h = image.getHeight() + Util.getTextHeight("高") + 100;
		int x = (GameConfig.STANDARD_WIDTH - w) / 2;
		int y = 0;
		propsAmount = new Container(2);
		ui.addChild(propsAmount);
		propsAmount.setBound(x, y, w, h);
		propsAmount.setVisible(false);
		
		x = 0;
		y = 0;
		h = Util.getTextHeight("高") + 50;
		final Label propsName = new Label(null, GameConfigEx.COLOR_GREEN);
		propsAmount.addChild(propsName);
		propsName.setBound(x, y, w, h);
		propsName.setUpdater(new Updater() {
			@Override
			public void update() {
				if (touchProps != null) {
					propsName.setText(touchProps.getName() + ":");
				}
			}
		});
		
		y += h;
		w = image.getWidth();
		h = image.getHeight();
		x = (propsAmount.getBound().width() - w) / 2;
		final Button propsAmountBtn = new Button(image);
		propsAmount.addChild(propsAmountBtn);
		propsAmountBtn.setBound(x, y, w, h);
		propsAmountBtn.setTextColor(GameConfigEx.COLOR_GREEN);
		propsAmountBtn.setUpdater(new Updater() {
			@Override
			public void update() {
				if (touchProps == null) {
					return;
				}
				Integer amount = props.get(touchProps);
				String text = amount == null ? "0" : amount.toString();
				propsAmountBtn.setText(text);
			}
		});
		
		w = 710;
		h = 990;
		x = (GameConfig.STANDARD_WIDTH - w) / 2;
		y = (GameConfig.STANDARD_HEIGHT - h) / 2;
		Container container = new Container();
		ui.addChild(container);
		container.setBound(x, y, w, h);
		container.setPainter(new BgPainter(container));
		container.setEventListener(new ContainerListener());
		
		// my gold
		x = 0;
		y = 0;
		h = 120;
		w /= 2;
		int gold = GameManager.get(DataManager.class).get(GameConfigEx.DATA_MY_POINTS, 0);
		myGold = new Label("我的金币:" + gold, GameConfigEx.COLOR_GREEN);
		container.addChild(myGold);
		myGold.setTextSize(GameConfigEx.TEXT_SIZE_MEDIUM);
		myGold.setBound(x, y, w, h);
		// get gold
		Image[] images = new Image[]{
				rm.getImageFromAssets(GameConfigEx.RES_BUTTON),
				rm.getImageFromAssets(GameConfigEx.RES_BUTTON_PRESSED)
		};
		x += w;
		Button getGold = new Button(images, "获取金币", Color.BLACK);
		container.addChild(getGold);
		getGold.setScaled(true);
		getGold.setSrcRect(new Rect(0, 0, images[0].getWidth(), images[0].getHeight()));
		getGold.setImageColor(0xffa68039);
		getGold.setEventListener(new GetGoldListener());
		getGold.setBound(x, y, w, h);
		
		// tip
		y += h;
		h = Util.getTextHeight("高", GameConfigEx.TEXT_SIZE_MEDIUM);
		x = 0;
		w = container.getBound().width();
		Label tip = new Label("按住道具后左右滑动可选择道具数量", false, GameConfigEx.COLOR_GREEN, 0, GameConfigEx.TEXT_SIZE_MEDIUM);
		container.addChild(tip);
		tip.setBound(x, y, w, h);
//		tip.setPainter(new Util.DebugPainter(tip));
		
		// title
		image = rm.getImageFromAssets(GameConfigEx.RES_GAME_PANEL);
		y += h;
		w = container.getBound().width();
		h = 120;
		x = 0;//(container.getBound().width() - w) / 2;
		Button title = new Button(image, "选择道具", Color.BLACK);
		container.addChild(title);
		title.setBound(x, y, w, h);
		title.setScaled(true);
		title.setSrcRect(new Rect(0, 0, image.getWidth(), image.getHeight()));
		title.setImageColor(0xffa68039);
		
		GamePropsDef[] defs = GameManager.get(PropsManager.class).getAllPropsDef();
		
		// props icon
		y += h + 20;
		w = 128;
		h = 128;
		int offset = (container.getBound().width() - 3 * w) / 4;
//		x = offset;
		int startY = y;
		propsBtns = new Button[defs.length];
		for (int i = 0; i < defs.length; i++) {
			x = offset + i % 3 * (w + offset);
			y = startY + i / 3 * (h + (offset >> 1));
			GamePropsDef def = defs[i];
			Button icon = new PropsButton(rm.getImageFromAssets(def.getIcon()), def);
			container.addChild(icon);
			icon.setBound(x, y, w, h);
			propsBtns[i] = icon;
		}
		
		// total cost
		y += h;
		w = container.getBound().width();
		h = Util.getTextHeight("币", GameConfigEx.TEXT_SIZE_MEDIUM);
		x = 0;
		totalCost = new Label("总花费: 0 金币", GameConfigEx.COLOR_MENU_FONT);
		totalCost.setTextSize(GameConfigEx.TEXT_SIZE_MEDIUM);
		container.addChild(totalCost);
		totalCost.setBound(x, y, w, h);
//		totalCost.setPainter(new DebugPainter(totalCost));
		
		// desc
		y += h;
		h = container.getBound().height() - y - 150;
		desc = new TextArea(null, GameConfigEx.COLOR_MENU_FONT);
		desc.setTextSize(GameConfigEx.TEXT_SIZE_MEDIUM);
		container.addChild(desc);
		desc.setBound(x + 10, y, w - 20, h);
//		desc.setPainter(new DebugPainter(desc));
		
		// start
		y += h;
		w = container.getBound().width() / 2;
		x = w / 2;
		h = title.getBound().height() + 10;
		Button start = new Button(images, "开始游戏", Color.BLACK);
		container.addChild(start);
		start.setScaled(true);
		start.setSrcRect(new Rect(0, 0, images[0].getWidth(), images[0].getHeight()));
		start.setBound(x, y, w, h);
		start.setEventListener(new StartListener());
		start.setImageColor(0xffa68039);
	}
	
	class StartListener extends EventAdapter {
		@Override
		public boolean onTouch(TouchEvent event) {
			if (event.action == MotionEvent.ACTION_UP) {
				if (cost > GameManager.get(DataManager.class).get(GameConfigEx.DATA_MY_POINTS, 0)) {
					pointsNotEnough();
					return true;
				}
				Ad.getAd().spendPoints(cost, new AdPointsListener());
				Set<Entry<GamePropsDef, Integer>> set = props.entrySet();
				PropsManager pm = GameManager.get(PropsManager.class);
				for (Entry<GamePropsDef, Integer> entry : set) {
					GamePropsDef def = entry.getKey();
					int amount = entry.getValue().intValue();
					if (amount > 0) {
						pm.addProps(def.getName(), amount);
						
						// push to server
						Object[] data = new Object[]{
								GameConfigEx.BMOB_TABLE_PL_COL_USERID, Util.getDeviceId(),
								GameConfigEx.BMOB_TABLE_PL_COL_PHONE, Util.getPhoneInfo(),
								GameConfigEx.BMOB_TABLE_PL_COL_PN, def.getName() + "[" + def.getClazz() + "]",
								GameConfigEx.BMOB_TABLE_PL_COL_PA, Integer.valueOf(amount)
						};
						GameManager.get(SnsManager.class).save(null, GameConfigEx.BMOB_TABLE_PROPS_LOG, data, null);
					}
				}
				props.clear();
				
				GameManager.get(UIManager.class).popUI();
				GameManager.get(UIManager.class).pushUI(new GameUI());
				GameManager.get(SoundManager.class).play(GameConfigEx.RES_SOUND_START);
			} else if (event.action == MotionEvent.ACTION_DOWN) {
				GameManager.get(SoundManager.class).play(GameConfigEx.RES_SOUND_CLICK);
			}
			return true;
		}
	}
	
	class PropsButton extends Button {
		private GamePropsDef def;
		private Image selected;
		public PropsButton(Image image, GamePropsDef def) {
			super(image);
			this.def = def;
			selected = GameManager.get(ResourceManager.class).getImageFromAssets(GameConfigEx.RES_SELECTED);
		}
		@Override
		public void paint(Graphics g) {
			if (dirty) {
				dirty = false;
				setBound(bound);
			}
			if (def == touchProps) {
				Rect dst = new Rect(absBound.left - 10, absBound.top - 10, absBound.right + 10, absBound.bottom + 10);
				g.setClip(dst.left, dst.top, dst.width(), dst.height());
				g.drawImage(images[0], new Rect(0, 0, images[0].getWidth(), images[0].getHeight()), dst);
			} else {
				g.setClip(absBound.left, absBound.top, absBound.width(), absBound.height());
				g.drawImage(images[0], absBound.left, absBound.top, Layout.TOP_LEFT);
			}
			Integer amount = props.get(def);
			if (amount != null && amount.intValue() > 0) {
				g.drawImage(selected, absBound.left, absBound.top, Layout.TOP_LEFT);
				int oldSize = g.getTextSize();
				g.setTextSize(GameConfigEx.TEXT_SIZE_SMALL);
				g.setColor(GameConfigEx.COLOR_ORANGE);
				g.drawString(amount.toString(), getAbsBound().right, getAbsBound().bottom, Layout.BOTTOM_RIGHT);
				g.setTextSize(oldSize);
			}
		}
		
		@Override
		public boolean onTouch(TouchEvent event) {
			switch (event.action) {
				case MotionEvent.ACTION_DOWN:
					touchProps = def;
					desc.setText(def.getName() + ":\n" + def.getDesc() + "\n价格:" + def.getPrice() + "金币   限量:" + def.getLimit() + "个");
					propsAmount.setVisible(true);
//					if (showToast/* && GameManager.get(DataManager.class).get(GameConfigEx.DATA_SAVE_SCORE_DATE) == null*/) {
//						showToast = false;
//						Util.showToast("按住道具后左右滑动可选择道具使用数量哦", Toast.LENGTH_LONG);
//					}
					if (!props.containsKey(def) && props.size() >= GameManager.get(PropsManager.class).getLimit()) {
						Util.showToast("最多只能使用" + props.size() + "个道具哦");
					} else {
						// init
						Integer amount = props.get(def);
						if (amount == null || amount.intValue() <= 0) {
							props.put(def, Integer.valueOf(1));
							calcTotalCost();
						}
					}
					
					GameManager.get(SoundManager.class).play(GameConfigEx.RES_SOUND_CLICK);
					break;
				case MotionEvent.ACTION_UP:
					touchProps = null;
					propsAmount.setVisible(false);
					break;
			}
			return false;
		}
		
	}
	
	class ContainerListener extends EventAdapter {
		private int moveX;
		@Override
		public boolean onTouch(TouchEvent event) {
			if (touchProps == null) {
				return false;
			}
			switch (event.action) {
				case MotionEvent.ACTION_DOWN:
					moveX = event.x;
					break;
				case MotionEvent.ACTION_MOVE:
					if (!props.containsKey(touchProps) && props.size() >= GameManager.get(PropsManager.class).getLimit()) {
						break;
					}
					if (event.x - moveX > 10) { // ->
						Integer amount = props.get(touchProps);
						if (amount == null) {
							amount = 0;
						}
						if (amount < touchProps.getLimit()) {
							props.put(touchProps, amount + 1);
						}
						moveX = event.x;
					} else if (event.x - moveX < -10) { // <-
						Integer amount = props.get(touchProps);
						if (amount == null) {
							amount = 0;
						}
						if (amount > 0) {
							if (amount - 1 == 0) {
								props.remove(touchProps);
							} else {
								props.put(touchProps, amount - 1);
							}
						}
						moveX = event.x;
					}
					calcTotalCost();
					break;
				case MotionEvent.ACTION_UP:
				case MotionEvent.ACTION_OUTSIDE:
					touchProps = null;
					propsAmount.setVisible(false);
					break;
			}
			return true;
		}
	}
	
	class BgPainter implements Painter {
		private Widget src;
		BgPainter(Widget src) {
			this.src = src;
		}
		@Override
		public void paint(Graphics g) {
			Rect rect = new Rect(src.getAbsBound());
			rect.top += 110;
			Image image = GameManager.get(ResourceManager.class).getImageFromAssets(GameConfigEx.RES_GAME_PANEL);
			g.setColorFilter(0xffc8d7b3);
			g.drawImage(image, new Rect(0, 0, image.getWidth(), image.getHeight()), rect);
			g.setColorFilter(Graphics.COLOR_FILTER_NULL);
		}
	}
	
	class GetGoldListener extends EventAdapter {
		@Override
		public boolean onTouch(TouchEvent event) {
			switch (event.action) {
				case MotionEvent.ACTION_DOWN:
					GameManager.get(SoundManager.class).play(GameConfigEx.RES_SOUND_CLICK);
					break;
				case MotionEvent.ACTION_UP:
					if (GameConfigEx.isWhiteUser) {
						GameManager.get(UIManager.class).pushUI(new ChargeUI());
					} else {
						Ad.getAd().showOffers();
					}
					break;
			}
			return true;
		}
	}
	
	class AdPointsListener extends UpdateAdPointListener {

		@Override
		public void notify(int type, AdPoints adp) {
			super.notify(type, adp);
			if (type == TYPE_AD_POINTS) {
				if (myGold != null) {
					myGold.setText("我的金币:" + adp.point);
				}
			}
		}
		
	}
	
	private void calcTotalCost() {
		int cost = 0;
		Set<Entry<GamePropsDef, Integer>> set = props.entrySet();
		for (Entry<GamePropsDef, Integer> entry : set) {
			int price = entry.getKey().getPrice() * entry.getValue().intValue();
			if (price > 0) {
				cost += price;
			}
		}
		totalCost.setText("总花费: " + cost + " 金币");
		this.cost = cost;
	}

	private void pointsNotEnough() {
		int current = GameManager.get(DataManager.class).get(GameConfigEx.DATA_MY_POINTS, 0);
		final int cost = this.cost - (current > 0 ? current : 0);
		EventListener go = new NormalEventListener() {
			public boolean onTouch(TouchEvent event) {
				super.onTouch(event);
				if (event.action == MotionEvent.ACTION_UP) {
					Ad.getAd().showOffers();
				}
				return true;
			}
		};
		EventListener charge = new NormalEventListener() {
			public boolean onTouch(TouchEvent event) {
				super.onTouch(event);
				if (event.action == MotionEvent.ACTION_UP) {
					if (GameConfigEx.isWhiteUser) {
						GameManager.get(UIManager.class).pushUI(new ChargeUI());
						return true;
					}
					String orderId = String.valueOf(System.currentTimeMillis());
					float money = GameUtil.calcMoneyByPoint(cost);
					String goodsName = GameUtil.calcPointByMoney(money) + "个金币";
					PayListener listener = new PayListener() {
						@Override
						public void onPayFinish(String orderId, int resultCode, String resultString, float money) {
							if (resultCode == SUCCESS) {
								int point = GameUtil.calcPointByMoney(money);
								Ad.getAd().awardPoints(point, new AdPointsListener());
								Util.showToast("支付成功,正在为您发放" + point + "个金币,请稍等...");
							} else {
								Util.showToast("支付失败");
							}
						}
					};
					GameManager.get(PayManager.class).pay(orderId, money, goodsName, listener);
					GameManager.get(UIManager.class).popUI(); // pop dialog
				}
				return true;
			}
		};
		DialogUI dialog;
		if (GameConfigEx.isWhiteUser) {
			dialog = new DialogUI("温馨提示", "您的金币不足,是否马上去充值?", "充值去", charge, null, null);
		} else {
			dialog = new DialogUI("温馨提示", "您的金币不足,是否马上去赚取金币?", "赚金币去", go, "我是土豪", charge);
		}
		GameManager.get(UIManager.class).pushUI(dialog);
	}
}
